package com.fantaike.algorithm.linear;

import java.util.Iterator;


/**
 * @author jishushen
 * @create 2021-09-12 15:34
 */
public class Stack<T> implements Iterable<T> {
    //记录首节点
    private final Node head;
    //栈中元素中的个数
    private int N;


    private class Node{
        public T item;
        public Node next;
        public Node(T item,Node next){
            this.item = item;
            this.next = next;
        }
    }
    public Stack(){
        this.head = new Node(null,null);
        this.N = 0;
    }
    //判断栈是否为空，是返回true，否返回false
    public boolean isEmpty(){
        return N == 0;
    }

    //获取栈中元素的个数
    public int size(){
        return N;
    }

    //向栈中压入元素t
    public void push(T t){
        //1.找到首节点指向的第一个节点
        Node oldFirst = head.next;
        //2.创建新的节点
        Node newNode = new Node(t, null);
        //3.让首节点指向新的节点
        head.next = newNode;
        //4.让新的节点指向原来的第一个节点
        newNode.next = oldFirst;
        //5.元素个数+1
        N++;
    }

    //弹出栈顶元素
    public T pop(){
        //1.找到首节点指向的第一个节点
        Node oldFirst = head.next;
        if(oldFirst == null){
            return null;
        }
        //2.首节点指向原来第一个节点的下一个节点
        head.next = oldFirst.next;
        //3.元素个数减一
        N--;
        //返回弹栈的元素
        return oldFirst.item;
    }

    @Override
    public Iterator<T> iterator() {
        return new SIterator();
    }

    private class SIterator implements Iterator<T>{
        private Node n;

        public SIterator(){
            this.n = head;
        }
        @Override
        public boolean hasNext() {
            return n.next != null;
        }
        @Override
        public T next() {
            n = n.next;
            return n.item;
        }
    }
}
